package com.vibeplayer.app.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.vibeplayer.app.R;
import com.vibeplayer.app.activity.LyricEditorActivity;
import com.vibeplayer.app.model.Song;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LyricEditFragment extends Fragment {

    private EditText editTextLyrics;
    private Button btnAddTimestamp;
    private Button btnSave;
    private Song currentSong;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_lyric_edit, container, false);
        
        editTextLyrics = view.findViewById(R.id.editTextLyrics);
        btnAddTimestamp = view.findViewById(R.id.btnAddTimestamp);
        btnSave = view.findViewById(R.id.btnSave);
        
        // 获取当前歌曲
        if (getActivity() instanceof LyricEditorActivity) {
            currentSong = ((LyricEditorActivity) getActivity()).getSong();
        }
        
        // 设置按钮点击事件
        btnAddTimestamp.setOnClickListener(v -> addTimestamp());
        btnSave.setOnClickListener(v -> saveLyrics());
        
        // 加载现有歌词
        loadExistingLyrics();
        
        return view;
    }
    
    /**
     * 加载现有歌词文件
     */
    private void loadExistingLyrics() {
        if (currentSong == null) {
            return;
        }
        
        String songPath = currentSong.getPath();
        String lrcPath = songPath.substring(0, songPath.lastIndexOf(".")) + ".lrc";
        File lrcFile = new File(lrcPath);
        
        if (lrcFile.exists()) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(lrcFile), "UTF-8"))) {
                StringBuilder content = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line).append("\n");
                }
                editTextLyrics.setText(content.toString());
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getContext(), R.string.no_lyric_file, Toast.LENGTH_SHORT).show();
            }
        } else {
            // 如果没有歌词文件，添加一些基本的元数据标签
            StringBuilder defaultContent = new StringBuilder();
            defaultContent.append("[ti:").append(currentSong.getTitle()).append("]\n");
            defaultContent.append("[ar:").append(currentSong.getArtist()).append("]\n");
            defaultContent.append("[al:").append(currentSong.getAlbum()).append("]\n");
            defaultContent.append("[by:VibePlayer]\n");
            defaultContent.append("[offset:0]\n\n");
            defaultContent.append(getString(R.string.edit_lyric_tip)).append("\n\n");
            
            editTextLyrics.setText(defaultContent.toString());
        }
    }
    
    /**
     * 添加时间戳
     */
    private void addTimestamp() {
        if (getActivity() instanceof LyricEditorActivity) {
            LyricEditorActivity activity = (LyricEditorActivity) getActivity();
            
            // 获取当前播放位置
            int currentPosition = 0; // 默认为0
            
            // 格式化时间戳
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss.SS", Locale.getDefault());
            String timestamp = "[" + sdf.format(new Date(currentPosition)).substring(0, 8) + "]";
            
            // 在光标位置插入时间戳
            int start = Math.max(editTextLyrics.getSelectionStart(), 0);
            Editable editable = editTextLyrics.getText();
            editable.insert(start, timestamp);
        }
    }
    
    /**
     * 保存歌词
     */
    private void saveLyrics() {
        if (currentSong == null) {
            return;
        }
        
        String songPath = currentSong.getPath();
        String lrcPath = songPath.substring(0, songPath.lastIndexOf(".")) + ".lrc";
        File lrcFile = new File(lrcPath);
        
        try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(lrcFile), "UTF-8")) {
            writer.write(editTextLyrics.getText().toString());
            Toast.makeText(getContext(), R.string.save_success, Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getContext(), R.string.save_failed, Toast.LENGTH_SHORT).show();
        }
    }
} 